package com.though.cos.soa;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import com.though.cos.config.CosConfig;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: Czh
 * Date: 2018/3/1
 * Time: 上午8:58
 */
public class CosManager {

    public static CosConfig config = new CosConfig();

    public static String default_bucket_name = "idc02-cos-coin-00";

    public static String request_url = "https://%s-%s.cosbj.myqcloud.com%s";


//    public static COSClient cosClient = new COSClient(new BasicCOSCredentials(config.getConfigParams().getSecretId(),
//            config.getConfigParams().getSecretKey()), new ClientConfig(new Region("ap-beijing")));

    /**
     *  上传文件
     * @param key filePath
     * @param inLen 文件字节长度
     */
    public static String upFileCos(String key, InputStream in, long inLen, String bucketName) throws InterruptedException,IOException{

//        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
//        ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));
        COSClient cosClient = new COSClient(new BasicCOSCredentials(config.getConfigParams().getSecretId(),
                config.getConfigParams().getSecretKey()),
                new ClientConfig(new Region("ap-beijing")));
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(inLen);
        objectMetadata.setContentType("image/png");

        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        TransferManager transferManager = new TransferManager(cosClient, threadPool);

        // 本地文件上传
        bucketName = StringUtils.isBlank(bucketName) ? config.getConfigParams().getBucketName() : bucketName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName + "-" + config.getConfigParams().getAppId(), key, in, objectMetadata);
        Upload upload = transferManager.upload(putObjectRequest);
        // 等待传输结束（如果想同步的等待上传结束，则调用 waitForCompletion）
        try {
            UploadResult uploadResult = upload.waitForUploadResult();
            //upload.waitForCompletion();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        transferManager.shutdownNow();

        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return String.format(request_url, StringUtils.isBlank(bucketName) ? default_bucket_name : bucketName, config.getConfigParams().getAppId(), key);
    }

    /**
     * 获取文件相对路径及名称
     */
    public static String processPathFile(FileTypeEnum fileType) {
        Random random = new Random();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        if (fileType == FileTypeEnum.JPG) {
            return "/jianhuo/image/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(10000)) + ".jpg";
        } else if (fileType == FileTypeEnum.PNG) {
            return "/jianhuo/image/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(10000)) + ".png";
        } else if (fileType == FileTypeEnum.MP4 || fileType == FileTypeEnum.FLV) {
            return "/jianhuo/video/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(10000)) + ".mp4";
        }
        return "";
    }



//    public static void main(String[] args) throws Exception {
//		File file = new File("/Users/though/Downloads/151055999225344.mp4");
//		InputStream in = new FileInputStream(file);
//		String key = processPathFile(FileTypeEnum.OTHER);
//		if (StringUtils.isBlank(key)) {
//            Random random = new Random();
//            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
//		    key = "/file/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(10000)) + file.getName().substring(file.getName().lastIndexOf("."));
//        }
//		System.out.println(upFileCos(key, in,in.available(),null));
//		// image/20170827/1503814605588466.png
//		//System.out.println(deleteFile(null, "image/20170827/201700000000.png"));
//	}
}